﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

#region Summary
    /*  This class is for debug only. Given an Asset File 
     *  it will search for Resource Tags like 
     *  [Texture]   //tag
     *  {
     *  Filename.....
     *  Filename.....
     *  Filename.....
     *  }
     *  All these filenames will be added into Texture List with Resource manager
     *  Similarly for Sound and Effects and later on Sprites and Animated Sprites or
     *  anything that our level will need
     *  The big plus is that if that resource changes at any time it will automatically
     *  reload the new file without the need to shut down the game.
     */
    #endregion

namespace Imagine
{
    
    class HotAssetLoader
    {
        public HotAssetLoader(ContentManager loader_)
        {
            m_contentLoader = loader_;
            m_timeStampMap = new Dictionary<string,DateTime>();
            m_AssetMap = new Dictionary<string,object>();
        }
        
        public T Load<T>(string path)
        {
            if(m_AssetMap.ContainsKey(path))
                return (T)m_AssetMap[path];

            T asset =  m_contentLoader.Load<T>(path);         
            m_AssetMap.Add(path,  asset);  

            return asset;
        }

        public T Get<T>(string path)
        {
            //You will cry if you give a wrong path :>)(hehehehe) GRIN...!!
            return (T)m_AssetMap[path];
        }

        //makes sure that if the file is again written to, our asset Loader reloads it 
        public void Refresh()
        {
           
             foreach( string key in  m_timeStampMap.Keys)
             {
                 
                 string str = Path.GetDirectoryName(key);
                 DateTime oldTime;
                 DateTime newTime = File.GetLastWriteTime(str);
                 m_timeStampMap.TryGetValue(key, out oldTime);
                 
                 if(newTime != oldTime)
                 {
                    m_AssetMap[key] = m_contentLoader.Load<object>(key);
                 }
             }
        }

        #region Private_Parts 
        
        ContentManager m_contentLoader;
        Dictionary<string, object>   m_AssetMap;
        Dictionary<string, DateTime> m_timeStampMap;

        #endregion
    }
}
